from django.utils.translation import gettext_lazy, gettext as _
from rest_framework.permissions import IsAuthenticated
from rest_framework.serializers import Serializer
from rest_framework.response import Response
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

from core import errors
from apps.api.paginations import NewPageNumberPagination100
from apps.api.viewsets import NormalGenericViewSet, serializer_error_msg
from apps.app_tx_meeting.managers import MeetingUserWrapper, NoShowWhitelistManager
from apps.app_tx_meeting import serializers
from apps.app_users.managers import get_user_by_name


class NoShowWhitelistViewSet(NormalGenericViewSet):
    """
    违约白名单时间
    """
    permission_classes = [IsAuthenticated]
    pagination_class = NewPageNumberPagination100
    lookup_field = 'id'

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('违约白名单记录查询'),
        manual_parameters=[
            openapi.Parameter(
                name='username',
                in_=openapi.IN_QUERY,
                required=False,
                type=openapi.TYPE_STRING,
                description=gettext_lazy('用户账号查询')
            ),
            openapi.Parameter(
                name='search',
                in_=openapi.IN_QUERY,
                required=False,
                type=openapi.TYPE_STRING,
                description=gettext_lazy('关键字查询，用户账号、姓名、备注')
            ),
        ],
        responses={
            200: ''''''
        }
    )
    def list(self, request, *args, **kwargs):
        """
        违约白名单记录查询

            * 需要管理员权限

            http code 200:
            {
                "count": 1,
                "page_num": 1,
                "page_size": 100,
                "results": [
                    {
                        "id": "najfi2gtok3xwfn9d014a0sey",
                        "username": "zhangsan@test.cn",
                        "user_nickname": "张三",
                        "remarks": "备注信息",
                        "creator": "lisi@test.cn",
                        "creation_time": "2025-09-09T03:19:08.594922Z",
                        "update_time": "2025-09-09T03:19:08.594981Z"
                    }
                ]
            }
        """
        username = request.query_params.get('username')
        search = request.query_params.get('search')

        try:
            mu = MeetingUserWrapper(user=request.user)
            if not mu.is_admin():
                raise errors.AccessDenied(message=_('你没有管理员权限'))

            qs = NoShowWhitelistManager.filter_whitelist_queryset(
                username=username, search=search
            )

            qs = qs.order_by('-creation_time')
            objs = self.paginate_queryset(qs)
            serializer = self.get_serializer(instance=objs, many=True)
            return self.get_paginated_response(serializer.data)
        except Exception as exc:
            return self.exception_response(exc)

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('添加用户到违约白名单'),
        responses={
            200: ''''''
        }
    )
    def create(self, request, *args, **kwargs):
        """
        添加用户到违约白名单

            * 需要管理员权限

            http code 200:
            {
                "id": "najfi2gtok3xwfn9d014a0sey",
                "username": "zhangsan@test.cn",
                "user_nickname": "张三",
                "remarks": "备注信息",
                "creator": "lisi@test.cn",
                "creation_time": "2025-09-09T03:19:08.594922Z",
                "update_time": "2025-09-09T03:19:08.594981Z"
            }

            http code 400、403、409:
            {
                "code": "TargetAlreadyExists".
                "message": "用户已存在于白名单中，不能重复添加。"
            }
            error code:
                AccessDenied: 你没有管理员权限
                TargetAlreadyExists: 用户已存在于白名单中，不能重复添加。
        """
        try:
            serializer = self.get_serializer(data=request.data)
            if not serializer.is_valid(raise_exception=False):
                msg = serializer_error_msg(serializer.errors)
                return self.exception_response(exc=errors.InvalidArgument(message=msg))

            data = serializer.validated_data
            username = data['username']
            user_nickname = data['user_nickname']
            remarks = data['remarks']

            mu = MeetingUserWrapper(user=request.user)
            if not mu.is_admin():
                raise errors.AccessDenied(message=_('你没有管理员权限'))

            # 白名单是否已存在用户
            if NoShowWhitelistManager.is_user_in_whitelist(username=username):
                raise errors.TargetAlreadyExists(message=_('用户已存在于白名单中，不能重复添加。'))

            # 尝试查询用户
            if not user_nickname:
                try:
                    wl_user = get_user_by_name(username=username)
                    user_nickname = wl_user.get_full_name()
                except Exception as exc:
                    pass

            obj = NoShowWhitelistManager.create_whitelist(
                username=username, user_nickname=user_nickname, remarks=remarks, creator=request.user.username
            )
            return Response(self.get_serializer(instance=obj).data, status=200)
        except Exception as exc:
            return self.exception_response(exc)

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('修改违约白名单记录'),
        responses={
            200: ''''''
        }
    )
    def update(self, request, *args, **kwargs):
        """
        修改违约白名单记录

            * 需要管理员权限

            http code 200:
            {
                "id": "najfi2gtok3xwfn9d014a0sey",
                "username": "zhangsan@test.cn",
                "user_nickname": "张三",
                "remarks": "备注信息",
                "creator": "lisi@test.cn",
                "creation_time": "2025-09-09T03:19:08.594922Z",
                "update_time": "2025-09-09T03:19:08.594981Z"
            }

            http code 400、403、409:
            {
                "code": "InvalidArgument".
                "message": "参数有误"
            }
            error code:
                AccessDenied: 你没有管理员权限
                TargetNotExist: 白名单用户记录不存在
                TargetAlreadyExists: 无修改记录，同名的用户已存在于白名单中。
        """
        try:
            serializer = self.get_serializer(data=request.data)
            if not serializer.is_valid(raise_exception=False):
                msg = serializer_error_msg(serializer.errors)
                return self.exception_response(exc=errors.InvalidArgument(message=msg))

            data = serializer.validated_data
            username = data['username']
            user_nickname = data['user_nickname']
            remarks = data['remarks']

            mu = MeetingUserWrapper(user=request.user)
            if not mu.is_admin():
                raise errors.AccessDenied(message=_('你没有管理员权限'))

            # 白名单记录是否已存
            obj = NoShowWhitelistManager.get_whitelist(wl_id=kwargs[self.lookup_field])
            if obj is None:
                raise errors.TargetNotExist(message=_('白名单用户记录不存在'))

            # 用户账号变更，创建人需要更新
            if obj.username != username:
                # 新用户白名单记录是否已存在
                if NoShowWhitelistManager.is_user_in_whitelist(username=username):
                    raise errors.TargetAlreadyExists(message=_('无修改记录，同名的用户已存在于白名单中。'))

                obj.creator = request.user.username

            # 尝试查询用户
            if not user_nickname:
                try:
                    wl_user = get_user_by_name(username=username)
                    user_nickname = wl_user.get_full_name()
                except Exception as exc:
                    pass

            obj.username = username
            obj.user_nickname = user_nickname if user_nickname else ''
            obj.remarks = remarks if remarks else ''
            obj.save(force_update=True)
            return Response(self.get_serializer(instance=obj).data, status=200)
        except Exception as exc:
            return self.exception_response(exc)

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('从违约白名单删除用户'),
        responses={
            204: ''''''
        }
    )
    def destroy(self, request, *args, **kwargs):
        """
        从违约白名单删除用户

            * 需要管理员权限

            http code 204: No Content

            http code 403、404:
            {
                "code": "AccessDenied",     # TargetNotExist: 白名单用户记录不存在
                "message": "你没有管理员权限"
            }
        """
        try:
            mu = MeetingUserWrapper(user=request.user)
            if not mu.is_admin():
                raise errors.AccessDenied(message=_('你没有管理员权限'))

            # 白名单是否已存在用户
            obj = NoShowWhitelistManager.get_whitelist(wl_id=kwargs[self.lookup_field])
            if obj is None:
                raise errors.TargetNotExist(message=_('白名单用户记录不存在'))

            obj.delete()
            return Response(status=204)
        except Exception as exc:
            return self.exception_response(exc)

    def get_serializer_class(self):
        if self.action in ['list', 'create', 'update']:
            return serializers.NoShowWhitelistSerializer

        return Serializer
